import OceanComponent from './OceanComponent';
import { DataTableColumn, NImage, NDataTable } from 'naive-ui';
import { format } from 'date-fns';

interface ITable<T> {
  column(title: string, key?: keyof T, props?: DataTableColumn);
  setData(data: TDataTableProps['data']): this;
}

class Table<T> extends OceanComponent<TDataTableProps> implements ITable<T> {
  columns: __Object[];
  selectedKeys: string[] = [];
  selectedRows: string[] = [];
  isOceanComponent = false;
  constructor(attrs?: TDataTableProps) {
    super(NDataTable, attrs, {
      columns: [],
      data: [],
      'on-update:checked-row-keys': (keys, rows) => {
        this.selectedKeys = keys;
        this.selectedRows = rows;
        this.attrs.onCheckedRow && this.attrs.onCheckedRow(keys, rows);
      }
    } as any);
    this.columns = this.attrs.columns;
  }
  column(title: string, key?: keyof T, props?: Partial<DataTableColumn>) {
    const column = Object.assign({}, { title, key }, props);

    const enums = enums => {
      (column as any).render = row => {
        return row[key] !== '' ? enums[row[key]] : row[key];
      };
    };
    const image = () => {
      (column as any).render = row => {
        let image = row[key];
        let src = Array.isArray(image) ? image[0] : image;
        return <NImage width={80} src={src ? src : '/images/default.jpg'}></NImage>;
      };
    };
    const date = (formatStr: string = 'yyyy-MM-dd') => {
      (column as any).render = (row: any) => format(row[key], formatStr);
    };

    const buttons = (buttons: TIconButtonsProps[]) => {
      (column as any).render = (row) =>
        <n-space>
          {
            buttons.map((btn: TIconButtonsProps) => {
              let _btn = { ...btn };
              _btn.onClick = btn.click ? () => btn.click(row) : null;
              _btn.disabled = typeof btn.disabled == 'function' ? btn.disabled(row) : btn.disabled;
              return <o-icon-button {..._btn} ></o-icon-button>
            })
          }
        </n-space>
    };

    this.columns.push(column);

    return {
      enums,
      image,
      date,
      buttons
    };
  }

  columnType(type: DataTableColumn['type']) {
    this.columns.push({ type });
  }

  define(column: Partial<DataTableColumn>) {
    this.columns.push(column);
  }

  setData(data: TDataTableProps['data']): this {
    this.data = data;
    return this;
  }

  get data() {
    return this.attrs.data;
  }

  set data(v: TDataTableProps['data']) {
    this.attrs.data = v;
  }
}

export default Table;
